import Router from 'koa-router';
import jwt from 'jsonwebtoken';
import { AdminUser } from '../models/index.js';
import { Sequelize } from 'sequelize';

const router = new Router({
  prefix: '/api/admin'
});

// 管理员登录
router.post('/login', async (ctx) => {
  const { username, password } = ctx.request.body;
  console.log('process.env', process.env.JWT_SECRET);
  const admin = await AdminUser.findOne({ where: { username } });
  
  if (!admin || !(await admin.validatePassword(password))) {
    console.log('username', username);
    console.log('password', password);
    ctx.throw(401, '用户名或密码错误');
  }

  const token = jwt.sign(
    { id: admin.id, role: admin.role },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  );

  ctx.body = {
    token,
    admin: {
      id: admin.id,
      username: admin.username,
      role: admin.role
    }
  };
});

// 验证管理员权限的中间件
const authMiddleware = async (ctx, next) => {
  try {
    const token = ctx.headers.authorization?.split(' ')[1];
    if (!token) {
      ctx.throw(401, '未提供认证令牌');
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    ctx.state.user = decoded;
    await next();
  } catch (error) {
    ctx.throw(401, '无效的认证令牌');
  }
};

// 验证超级管理员权限的中间件
const adminAuthMiddleware = async (ctx, next) => {
  if (ctx.state.user.role !== 'admin') {
    ctx.throw(403, '权限不足');
  }
  await next();
};

// 获取管理员列表（需要管理员权限）
router.get('/users', authMiddleware, adminAuthMiddleware, async (ctx) => {
  const admins = await AdminUser.findAll({
    attributes: ['id', 'username', 'role', 'status', 'createdAt']
  });
  ctx.body = admins;
});

// 获取指定管理员信息
router.get('/users/:id', authMiddleware, async (ctx) => {
  const { id } = ctx.params;
  
  const admin = await AdminUser.findOne({
    where: {
      [Sequelize.Op.or]: [
        { id: isNaN(id) ? 0 : id },
        { username: id }
      ]
    },
    attributes: ['id', 'username', 'role', 'status', 'createdAt', 'updatedAt']
  });

  if (!admin) {
    ctx.throw(404, '管理员不存在');
  }

  // 如果不是超级管理员，只能查看自己的信息
  if (ctx.state.user.role !== 'admin' && ctx.state.user.id !== admin.id) {
    ctx.throw(403, '权限不足');
  }

  ctx.body = admin;
});

// 获取当前登录管理员信息
router.get('/profile', authMiddleware, async (ctx) => {
  const admin = await AdminUser.findByPk(ctx.state.user.id, {
    attributes: ['id', 'username', 'role', 'status', 'createdAt', 'updatedAt']
  });

  if (!admin) {
    ctx.throw(404, '管理员不存在');
  }

  ctx.body = admin;
});

// 创建新管理员（需要超级管理员权限）
router.post('/users', authMiddleware, adminAuthMiddleware, async (ctx) => {
  const { username, password, role } = ctx.request.body;
  const admin = await AdminUser.create({ username, password, role });
  ctx.body = {
    id: admin.id,
    username: admin.username,
    role: admin.role
  };
});

// 更新管理员状态
router.put('/users/:id/status', authMiddleware, adminAuthMiddleware, async (ctx) => {
  const { id } = ctx.params;
  const { status } = ctx.request.body;
  
  const admin = await AdminUser.findByPk(id);
  if (!admin) {
    ctx.throw(404, '管理员不存在');
  }
  
  await admin.update({ status });
  ctx.body = {
    id: admin.id,
    username: admin.username,
    status: admin.status
  };
});

export default router;